import socket
import fcntl
import struct

def get_interface_index(interface_name):
    """
    获取指定网络接口的索引（接口编号）。
    
    :param interface_name: 网络接口名称，如"eth0"
    :return: 接口索引，如果失败则返回None
    """
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return fcntl.ioctl(sock.fileno(), 0x8933,  # SIOCGIFINDEX for getting the interface index
                           struct.pack('256s', interface_name.encode('utf-8')))[20:24][::-1]
    except OSError as e:
        print(f"Error getting interface index for {interface_name}: {e}")
        return None
    finally:
        sock.close()

# 使用方法
interface_index = get_interface_index("eth2")
if interface_index:
    print(f"The index of interface 'eth0' is: {socket.ntohs(interface_index[0])}")
else:
    print("Failed to get the interface index.")